<template>
  <page-header-wrapper>
    <page-tab-list>
      <div class="table-page-search-box">
        <a-form layout="inline">
          <a-row :gutter="24">
            <a-col :md="8" :sm="24">
              <a-form-item label="姓名/昵称">
                <a-input allowClear v-model="queryParam.keyword" placeholder="姓名/昵称" />
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="分销商类型">
                <a-select placeholder="选择分销商" v-model="queryParam.platform">
                  <a-select-option value="-1">全部分销商</a-select-option>
                  <a-select-option value="1">支付宝</a-select-option>
                  <a-select-option value="0">微信</a-select-option>
                  <a-select-option value="2">公众号</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="">
                <a-button type="primary" @click="$refs.table.refresh(true)">查询</a-button>
              </a-form-item>
            </a-col>
          </a-row>
        </a-form>
      </div>
    </page-tab-list>
    <a-card :bordered="false">
      <div class="table-operator" style="display: flex; justify-content: space-between">
        <span></span>
        <a-button type="primary" @click="addPop = true">+ 添加</a-button>
      </div>
      <s-table
        ref="table"
        :rowKey="
          (r, i) => {
            return i
          }
        "
        :columns="columns"
        :data="loadData"
        showPagination="auto"
      >
        <!-- 基本信息 -->
        <span slot="baseinfo" slot-scope="text, record">
          <a-space>
            <img style="width: 48px; heigth: 48px" :src="record.avatar_url" />
            <span>
              <a-tooltip>
                <template slot="title">
                  {{ record.nickname }}
                </template>
                <a-row
                  ><div class="over_e">{{ record.nickname }}</div></a-row
                >
              </a-tooltip>
              <a-row v-if="record.platform == 0">微信</a-row>
              <a-row v-if="record.platform == 1">支付宝</a-row>
              <a-row v-if="record.platform == 2">公众号</a-row>
            </span>
          </a-space>
        </span>
        <!-- 手机号 -->
        <span slot="wayinfo" slot-scope="text, record">
          <div>{{ text || '-' }}</div>
          <div>{{ record.mobile || '-' }}</div>
        </span>
        <!-- 累计佣金 -->
        <span slot="total_price" slot-scope="text">
          <a-space>¥{{ text }} </a-space>
        </span>
        <!-- 可提佣金 -->
        <span slot="price" slot-scope="text">
          <a-space>¥{{ text }} </a-space>
        </span>
        <!-- 审核时间 -->
        <span slot="time" slot-scope="text, record">
          <!-- <a-space> 申请时间：{{ text }} </a-space> -->
          <a-space>{{ record.updated_at }} </a-space>
        </span>
        <!-- 下级 -->
        <span slot="level" slot-scope="record">
          {{ record.first.count + record.second.count + record.third.count }}
        </span>

        <!-- <span slot="status" slot-scope="status">
          <a-badge
            :status="status == 0 ? 'default' : status == 1 ? 'processing' : 'error'"
            :text="status == 0 ? '未审核' : status == 1 ? '审核通过' : '已拒绝'"
          />
        </span> -->
        <!-- 操作 -->
        <span slot="action" slot-scope="text, record">
          <template v-if="record.status == 0">
            <a-space>
              <a @click="handleStatus(record, 1)">通过</a>
              <a-divider type="vertical" />
              <a @click="handleStatus(record, 2)">拒绝</a>
            </a-space>
          </template>
          <template v-if="record.status == 1">
            <a-space>
              <a @click="$router.push({ name: 'ShareDistributorDetail', query: { id: record.user_id } })">查看</a>
              <a-divider type="vertical" />
              <template>
                <a-dropdown>
                  <a class="ant-dropdown-link" @click="(e) => e.preventDefault()"> 更多<a-icon type="down" /> </a>
                  <a-menu slot="overlay">
                    <a-menu-item>
                      <a @click="jump(record, 2)">提现明细</a>
                    </a-menu-item>
                    <a-menu-item>
                      <a @click="jump(record, 1)">分销订单</a>
                    </a-menu-item>
                    <a-menu-item>
                      <a-popconfirm title="确认删除该分销商吗？" @confirm="handleDelete(record)">
                        <a>删除</a>
                      </a-popconfirm>
                    </a-menu-item>
                    <a-menu-item>
                      <a @click="qrcode(record.user_id)">分销二维码</a>
                    </a-menu-item>
                    <a-menu-item>
                      <a-popconfirm @confirm="setComments(record)">
                        <template slot="title">
                          <p>备注</p>
                          <a-input v-model="sellerComments" placeholder="请输入备注" />
                        </template>
                        <a>备注</a>
                      </a-popconfirm>
                    </a-menu-item>
                    <a-menu-item>
                      <a @click="openLevel(record)">设置等级</a>
                    </a-menu-item>
                  </a-menu>
                </a-dropdown>
              </template>
            </a-space>
          </template>
        </span>
      </s-table>
    </a-card>

    <a-modal v-model="visible" title="下级用户">
      <table>
        <tr>
          <th class="table-style">序号</th>
          <th class="table-style">分销商</th>
          <th class="table-style">下线等级</th>
          <th class="table-style">昵称</th>
        </tr>
        <tr
          v-if="now_level == 1 && first.length > 0"
          :value="item.nickname"
          v-for="(item, index) of first"
          :key="index"
        >
          <td class="table-style">{{ index }}</td>
          <td class="table-style">{{ records.nickname }}</td>
          <td class="table-style">一级</td>
          <td class="table-style">{{ item }}</td>
        </tr>
        <tr
          v-if="now_level == 2 && second.length > 0"
          :value="item.nickname"
          v-for="(item, index) of second"
          :key="index"
        >
          <td class="table-style">{{ index }}</td>
          <td class="table-style">{{ records.nickname }}</td>
          <td class="table-style">二级</td>
          <td class="table-style">{{ item }}</td>
        </tr>
        <tr
          v-if="now_level == 3 && third.length > 0"
          :value="item.nickname"
          v-for="(item, index) of third"
          :key="index"
        >
          <td class="table-style">{{ index }}</td>
          <td class="table-style">{{ records.nickname }}</td>
          <td class="table-style">三级</td>
          <td class="table-style">{{ item }}</td>
        </tr>
      </table>
    </a-modal>
    <a-modal v-model="addPop" @ok="submitForm" title="添加" :afterClose="closeAddPop">
      <a-form-model ref="ruleForm" :model="form" :rules="rules" :label-col="{ span: 6 }" :wrapper-col="{ span: 14 }">
        <a-form-model-item label="选择用户" prop="nickName">
          <a-input :disabled="true" placeholder="请选择用户" v-model="form.nickName" style="width: 150px"></a-input>
          <a-button type="primary" style="margin-left: 10px" @click="openPop('add')">选择</a-button>
        </a-form-model-item>
        <a-form-model-item label="姓名" prop="name">
          <a-input v-model="form.name" placeholder="请输入名称" />
        </a-form-model-item>
        <a-form-model-item label="手机号" prop="mobile">
          <a-input v-model="form.mobile" placeholder="请输入手机号" />
        </a-form-model-item>
      </a-form-model>
    </a-modal>

    <!-- 更换上级的弹窗 -->
    <a-modal
      title="选择用户"
      zIndex="9999"
      style="width: 300px"
      v-model="userVisible"
      :destroyOnClose="true"
      :footer="null"
    >
      <div style="margin-bottom: 10px">
        <a-input-search
          placeholder="输入昵称搜索"
          v-model="keyword"
          allowClear
          enter-button
          @search="$refs.table_.refresh(true)"
        />
      </div>
      <s-table ref="table_" rowKey="id" :columns="manager" :data="loadData_">
        <span slot="baseinfo" slot-scope="text, record">
          <img style="width: 40px; heigth: 40px; border-radius: 3px; margin-right: 5px" :src="record.avatar" />
          <span :length="20" tooltip>{{ record.name }}</span>
        </span>
        <span slot="action" slot-scope="text, record">
          <a-button type="primary" size="small" @click="onSelect(record)"> 选择 </a-button>
        </span>
      </s-table>
    </a-modal>
    <a-modal v-model="qrcode_visiable" title="分销二维码" :footer="null">
      <img :src="qrcode_img" />
    </a-modal>

    <a-modal title="修改等级" @ok="changeLevel" style="width: 300px" v-model="levelPop">
      <a-select placeholder="" v-model="level" style="width: 100%">
        <a-select-option v-for="item of share_level" :value="item.id" :key="item.id">{{ item.name }}</a-select-option>
      </a-select>
    </a-modal>
  </page-header-wrapper>
</template>

<script>
import { STable, Ellipsis } from '@/components'
import { setDel, setAudit, setComments, shareUserList, getQrcode, addShare, setShareLevel } from '@/api/share'
import NoBorderRadio from '@/components/NoBorderRadio/NoBorderRadio'
import { getSelectUserList } from '@/api/user'
import storage from 'store'

const columns = [
  {
    title: '用户ID',
    dataIndex: 'user_id',
    scopedSlots: { customRender: 'user_id' },
    width: 80,
  },
  {
    title: '基本信息',
    dataIndex: 'nickname',
    width: 200,
    scopedSlots: { customRender: 'baseinfo' },
    ellipsis: true,
  },
  {
    title: '手机号',
    dataIndex: 'name',
    // width: 150,
    scopedSlots: { customRender: 'wayinfo' },
  },
  {
    title: '等级',
    dataIndex: 'level_name',
  },
  {
    title: '累计佣金',
    dataIndex: 'total_price',
    // width: 165,
    scopedSlots: { customRender: 'total_price' },
    sorter: (a, b) => a.total_price - b.total_price,
  },
  {
    title: '可提佣金',
    dataIndex: 'price',
    // width: 165,
    scopedSlots: { customRender: 'price' },
    sorter: (a, b) => a.price - b.price,
  },
  {
    title: '推荐人',
    dataIndex: 'parent_nickname',
    ellipsis: true,
    // width: 80,
  },
  {
    title: '下级用户',
    scopedSlots: { customRender: 'level' },
    // width: 120,
  },
  //   {
  //     title: '状态',
  //     dataIndex: 'status',
  //     scopedSlots: { customRender: 'status' },
  //     // width: 100,
  //   },
  {
    title: '审核时间',
    dataIndex: 'updated_at',
    scopedSlots: { customRender: 'time' },
    sorter: (a, b) => a.updated_at - b.updated_at,
  },
  {
    title: '操作',
    dataIndex: 'action',
    scopedSlots: { customRender: 'action' },
    width: 180,
  },
]

const manager = [
  {
    title: 'ID',
    dataIndex: 'id',
  },
  {
    title: '用户信息',
    scopedSlots: { customRender: 'baseinfo' },
  },
  {
    title: '操作',
    scopedSlots: { customRender: 'action' },
  },
]

export default {
  name: 'ShareUserList',
  components: {
    STable,
    Ellipsis,
    NoBorderRadio,
  },
  data() {
    this.columns = columns
    return {
      options: [
        {
          title: '全部',
          value: -1,
        },
        {
          title: '未审核',
          value: 0,
        },
        {
          title: '审核通过',
          value: 1,
        },
        {
          title: '审核拒绝',
          value: 2,
        },
      ],
      qrcode_img: '',
      qrcode_visiable: false,
      now_level: String,
      // create model
      visible: false,
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
      records: {},
      first: {},
      second: {},
      third: {},
      // 高级搜索 展开/关闭
      advanced: false,
      // 查询参数
      queryParam: {
        keyword: null,
        phone: null,
        // 分销商类型
        platform: '-1',
      },
      sellerComments: '',
      tabKey: '',
      // 加载数据方法 必须为 Promise 对象
      loadData: (parameter) => {
        Object.assign(parameter, this.queryParam)
        console.log('loadData request parameters:', parameter)
        parameter = { ...parameter, status: 1 }
        return shareUserList(parameter).then((res) => {
          console.log('res,', res)
          this.share_level = res.data.share_level
          return res.data
        })
      },
      loadData_: (parameter) => {
        let { type } = this,
          params

        params = {
          type: 'share',
        }

        return getSelectUserList({
          ...parameter,
          ...params,
          storeId: storage.get('storeId'),
          keyword: this.keyword,
        }).then((res) => {
          return res.data
        })
      },
      selectedRowKeys: [],
      selectedRows: [],
      addPop: false,
      form: {
        nickName: '',
        mobile: '',
        name: '',
        user_id: '',
      },
      keyword: '',
      type: '',
      parent_type: '',
      userVisible: false,
      manager,

      levelPop: false,
      levelId: '',
      level: '',
      share_level: [],
    }
  },
  filters: {},
  created() {},
  watch: {
    selectedRowKeys(newValue, oldValue) {
      console.log(newValue, oldValue)
    },
  },
  computed: {
    rowSelection() {
      return {
        selectedRowKeys: this.selectedRowKeys,
        onChange: this.onSelectChange,
      }
    },
  },
  methods: {
    openLevel({ id, level }) {
      this.levelId = id
      this.level = String(level)
      this.levelPop = true
    },

    async changeLevel() {
      const hide = this.$message.loading('取消中...', 0)

      let { level, levelId: id } = this
      const res = await setShareLevel({
        level,
        id,
      })
      hide()
      if (res.code !== 0) {
        this.$error({
          content: res.msg,
        })
      } else {
        this.levelPop = false
        this.$message.success(res.msg)
        this.$refs.table.refresh()
      }
    },

    // 选择用户
    onSelect(e) {
      let { type } = this
      if (type === 'edit') {
        if (this.parent_type == 1) {
          this.oldParentName = e.name
          this.editForm.old_saas_user_id = e.id
        } else {
          this.parentName = e.name
          this.editForm.saas_user_id = e.id
        }
      } else {
        this.form.nickName = e.name
        this.form.user_id = e.id

        this.$refs.ruleForm.validateField('nickName')
      }

      this.userVisible = false
    },
    openPop(type, parent_type) {
      this.type = type
      this.parent_type = parent_type
      this.userVisible = true
    },
    closeAddPop() {
      this.$refs.ruleForm.resetFields()
    },
    submitForm() {
      if (this.modalLoading) return
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          let form = JSON.parse(JSON.stringify(this.form))

          let params = {
            name: form.name,
            user_id: form.user_id,
            mobile: form.mobile,
          }

          this.modalLoading = true

          addShare(params)
            .then((res) => {
              this.modalLoading = false
              this.addPop = false
              if (res.code === 0) {
                this.$message.success(res.msg)

                this.$refs.table.refresh()
                this.userVisible = false
                return
              }

              this.$message.error(res.msg)
            })
            .catch((err) => {
              this.$message.error(err.message)
              this.modalLoading = false
            })
        }
      })
    },
    qrcode(val) {
      console.log(val)
      var params = {
        user_id: val,
      }
      getQrcode(params)
        .then((res) => {
          if (res.code !== 0) {
            this.$error({
              content: res.msg,
            })
          } else {
            this.qrcode_img = res.data.url
            this.qrcode_visiable = true
          }
        })
        .catch((err) => {
          this.$message.error(err.message)
        })
    },
    onSelectChange(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },
    toggleAdvanced() {
      this.advanced = !this.advanced
    },
    resetSearchForm() {
      this.queryParam = {}
    },
    tabChange(key) {
      this.queryParam.status = key
      this.$refs.table.refresh(true)
    },
    getLevel(record, level) {
      this.records = record
      this.first = record.first.team
      this.second = record.second.team
      this.third = record.third.team
      this.now_level = level
      this.visible = true
    },
    setComments(record) {
      var params = {
        id: record.id,
        seller_comments: this.sellerComments,
      }
      setComments(params)
        .then((res) => {
          if (res.code !== 0) {
            this.$error({
              content: res.msg,
            })
          } else {
            this.$message.success('备注成功')
            this.$refs.table.refresh()
          }
          this.sellerComments = ''
        })
        .catch((err) => {
          this.$message.error(err.message)
        })
    },
    handleStatus(record, status) {
      var params = {
        id: record.id,
        status: status,
      }
      var returnMsg = '拒绝成功！'
      if (status === 1) {
        returnMsg = '通过成功！'
      }
      setAudit(params).then((res) => {
        this.modalLoading = false
        if (res.code !== 0) {
          this.$error({
            content: res.msg,
          })
        } else {
          this.$refs.table.refresh()
          this.$message.success(returnMsg)
        }
      })
    },
    handleDelete(record) {
      var params = {
        id: record.id,
      }
      setDel(params).then((res) => {
        this.modalLoading = false
        if (res.code !== 0) {
          this.$error({
            content: res.msg,
          })
        } else {
          this.$refs.table.refresh()
          this.$message.success('删除成功！')
        }
      })
    },
    jump(record, type) {
      if (type === 1) {
        this.$router.push({ name: 'ShareOrder', query: { parent_id: record.user_id } })
      } else {
        this.$router.push({ name: 'ShareCash', query: { id: record.id } })
      }
    },
  },
}
</script>
<style lang="less" scoped>
.top_card {
  /deep/.ant-card-body {
    padding-bottom: 0;
  }
  /deep/.ant-tabs-bar {
    margin-bottom: 0;
    border-bottom: 1px solid #fff;
  }
}
.button_style {
  margin-top: 3px;
}
.table-style {
  padding: 0 30px;
}
.over_e {
  width: 90px;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}
</style>
